package com.cictec.middleware.tde.rm.mina.filter;

import java.util.Date;
import java.util.HashSet;
import java.util.Set;

import org.apache.mina.core.filterchain.IoFilterAdapter;
import org.apache.mina.core.session.IoSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.cictec.middleware.commons.utils.PMSUtils;
import com.cictec.middleware.tde.rm.protocol.TerminalMessage;
import com.cictec.middleware.tde.rm.protocol.TerminalMessage.Header;
import com.cictec.middleware.tde.rm.protocol.rm.message.Rm0x80PlatformMessage;

/**
 * 对收到的消息自动进行反馈处理。 需要进行自动反馈处理的指令需要在配合文件中指定。
 * 
 * @author Zhibin
 *
 */
@Component
public class AutoResponseFilter extends IoFilterAdapter {

	private static Logger logger = LoggerFactory.getLogger(AutoResponseFilter.class);
	
	/**
	 * 需要自动反馈处理的的消息ID。
	 */
	private Set<Integer> autoResponseMessages;

	public AutoResponseFilter() {

		Set<Integer> autoResponseMessages = new HashSet<Integer>();
		autoResponseMessages.add(0x01);
		autoResponseMessages.add(0x02);
		autoResponseMessages.add(0x03);
		setAutoResponseMessages(autoResponseMessages);

		if (logger.isDebugEnabled()) {
			String str = null;
			for (Integer integer : autoResponseMessages) {
				String messageId = PMSUtils.addZeroLForString(String.valueOf(Integer.toHexString(integer)), 2);
				str = str == null ? "0x"+messageId : str + ",0x"+messageId;
			}
			logger.debug("【AutoResponseFilter】【锐明】设置自动回复指令集 {}", str);
		}

	}
	
	@Override
	public void messageReceived(NextFilter nextFilter, IoSession session, Object message) throws Exception {
		TerminalMessage msg = (TerminalMessage) message;

		if (autoResponseMessages.contains(msg.getMessageId())) {
			session.write(createResponse(msg));
		}

		nextFilter.messageReceived(session, message);
	}

	/**
	 * 根据收到的消息创建反馈消息。
	 * 
	 * @param msg
	 * @return
	 */
	private Rm0x80PlatformMessage createResponse(TerminalMessage msg) {

		Integer messageId = msg.getMessageId();
		// 【0：自动应答 1：手动应答】【当所应答的数据包为连接请求时，应答类型中的 0 表示禁止连接，1 表示允许连接】
		int responseType = 1;
		if (messageId == 0x01) {
			responseType = 1;
		}

		Header header = new Header(0x80);

		msg.getMessageId();

		header.setLineId(msg.getHeader().getLineId());
		header.setTerminalId(msg.getHeader().getTerminalId());
		header.setDataFlag(0);

		Rm0x80PlatformMessage pr = new Rm0x80PlatformMessage(header);
		pr.setResponseMessageId(msg.getHeader().getMessageId());
		pr.setResponseMessageSequence(msg.getHeader().getMessageSequence());
		pr.setResponseTime(new Date());
		pr.setResponseType(responseType);
		pr.setSessionId(msg.getSessionId());

		return pr;

	}

	public Set<Integer> getAutoResponseMessages() {
		return autoResponseMessages;
	}

	public void setAutoResponseMessages(Set<Integer> autoResponseMessages) {
		this.autoResponseMessages = autoResponseMessages;
	}
}
